import axios from 'axios'
import { Message } from 'element-ui'
import store from '@neu/biz-core/store'
import { getToken } from '@neu/biz-core/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['Authentication'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authentication'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if status value is failure, it is judged as an error.
    if (res.status === 'failure') {
      Message({
        message: res.data || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(new Error(res.data || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error(error) // for debug
    const httpStatus = error.response.status
    if (httpStatus === 403) {
      Message({
        message: '会话过期，请重新登录！',
        type: 'error',
        duration: 5 * 1000
      })
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    } else if (httpStatus === 401) {
      Message({
        message: error.response.data.data,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
